package com.zyh.day03

import org.junit.Test

class CollectionTest {
  @Test
  def foreachTest(): Unit = {
    val list = List(1, 2, 3, 4, 5)
    list.foreach(v=>println(v))
    list.foreach(println(_))
    list.foreach(println)
  }

  @Test
  def mapTest(): Unit = {
    val list = List(1, 2, 3, 4, 5)
    val result: List[Int] = list.map(v => v + 10)
    result.foreach(println)
  }

  @Test
  def flattenTest(): Unit = {
    val list = List("hello world", "b bb", "c cc")
    list.map(item=>item.split(" "))
    val result: List[String] = list.map(item => item.split(" ")).flatten
    result.foreach(println)
  }

  @Test
  def flatMapTest(): Unit = {
    val list = List("hello world", "b bb", "c cc")
    val result: List[String] = list.flatMap(item => item.split(" "))
    result.foreach(println)
  }

  @Test
  def filterTest(): Unit = {
    val list = List(1,2,3,4,5)
    val result: List[Int] = list.filter(item => item % 2 == 0)
    result.foreach(println)
  }

  @Test
  def reduceTest(): Unit = {
    val list = List(1, 2, 3, 4, 5, 6, 7)
    //接受一个低阶函数(total,item)=>对集合中的元素进行处理
    /**
     * reduce 仍然遍历集合获取每个元素
     * 第一次调用低阶函数:total赋值为集合中第一个元素值 item赋值为第二个元素值 total=1 item=2
     * 从第二次调用开始:total被赋值为上一次执行的结果item被赋值为下一个元素值 total = 3 item = 3
     */
    println(list.reduce((total, item) => total + item))//总和
    println(list.reduce((total, item) => total * item))//总乘
    val maxValue: Int = list.reduce((total, item) => {
      if (total > item) total else item
    })
    println(s"maxValue = ${maxValue}")
  }
  
  @Test
  def foldTest(): Unit = {
    val list = List(1, 2, 3, 4, 5, 6, 7)

    /**
     * 第一次调用低阶函数 total = 10 item = 1
     */
    val result: Int = list.fold(10)((total, item) => total + item)
    println(s"result = ${result}")
  }

  @Test
  def sortedTest(): Unit = {
    val list = List(4, 6, 8, 1, 3, 4, 5)
    //默认升序
    val sorted: List[Int] = list.sorted
    println(sorted)
    sorted.foreach(println)

    //降序
    val reverse: List[Int] = list.sorted.reverse
    println(reverse)
  }

  @Test
  def sortByTest(): Unit = {
    val list = List(("张三",100),("李四",84),("王五",95),("赵六",30))
    //sortBy接受低阶函数 低阶函数用于返回排序依据
    val tuples: List[(String, Int)] = list.sortBy(t => t._2)
    println(tuples)
    val tuplesDesc: List[(String, Int)] = list.sortBy(t => t._2)(Ordering.Int.reverse)
    println(tuplesDesc)

    //先按_2降序再按_3升序
    var list2 = List(("张三",100,58),("李四",84,96),("王五",84,75),("赵六",30,61))
    val tuples2: List[(String, Int, Int)] = list2.sortBy(t => (t._2, t._3))(Ordering.Tuple2(Ordering.Int.reverse, Ordering.Int))
    println(tuples2)
  }

  @Test
  def groupByTest(): Unit = {
    var list = List(("张三",100),("张三",96),("李四",84),("李四",30))
    //groupBy接受的低阶函数处理每一个元素,返回分组依据
    val map: Map[String, List[(String, Int)]] = list.groupBy(t => t._1)
    println(map)
  }
}
